import React, {useState, useEffect} from 'react'
import {AsyncStorage} from 'react-native'
import {WithShareState} from './shareState'
let persistKeys: String[] = []
const setKeysListeners = new Set<Func>()
const ready = (persistKey: string) => {
  persistKeys = persistKeys.filter(key => key !== persistKey)
  setKeysListeners.forEach(setKey => setKey(persistKeys))
}
export const withStore = <T extends object>(initValue: T, persistKey: string) => {
  persistKeys.push(persistKey)
  let shareState = WithShareState(initValue)
  // shareState.addListener(data => {
  //   AsyncStorage.setItem(persistKey, JSON.stringify(data))
  // })
  // AsyncStorage.getItem(persistKey)
  //   .then(data => {
  //     if (data) {
  //       shareState.setShareState(JSON.parse(data))
  //     }
  //   })
  //   .finally(() => ready(persistKey))
  return shareState
}
export const useStoreIsReady = () => {
  const [keys, setKeys] = useState(persistKeys)
  useEffect(() => {
    setKeysListeners.add(setKeys)
    return () => setKeysListeners.delete(setKeys)
  }, [])
  return !keys.length
}
